
Partial Class admin_BudgetCategoryHeadings
    Inherits System.Web.UI.Page

    Private Const MAX_TOTAL_COLUMN_SPAN_SPENDINGPLAN As Integer = 10
    Private Const MAX_TOTAL_COLUMN_SPAN_MONTHLYSTATEMENT As Integer = 11

    Private Const GRIDHEADER_DISPLAYNAME As Integer = 0
    Private Const GRIDHEADER_SHOWONSPENDINGPLAN As Integer = 1
    Private Const GRIDHEADER_SHOWONEXPENDITUREREPORT As Integer = 2
    Private Const GRIDHEADER_COLUMNWIDTH As Integer = 3
    Private Const GRIDHEADER_DISPLAYORDER As Integer = 4
    Private Const GRIDHEADER_COLUMNSPAN As Integer = 5
    Private Const GRIDHEADER_FORMULA As Integer = 6
    Private Const GRIDHEADER_EXPENDITUREFORMULA As Integer = 7

    Private Const NEWVALUES_DISPLAYNAME As Integer = 0
    Private Const NEWVALUES_COLUMNWIDTH As Integer = 1
    Private Const NEWVALUES_DISPLAYORDER As Integer = 2
    Private Const NEWVALUES_COLUMNSPAN As Integer = 3
    Private Const NEWVALUES_FORMULA As Integer = 4
    Private Const NEWVALUES_EXPENDITUREFORMULA As Integer = 5

    Private message As String
    Private isError As Boolean

    Protected Sub Page_Load(ByVal sender As Object, _
                            ByVal e As System.EventArgs) _
                            Handles Me.Load
        ClearStatus()
        SetUpJavascript()
        Me.ErrorSummary.Visible = False
        If Not Page.IsPostBack Then
            Me.CategoryHeadingsScrollingGridView.Sort("DisplayOrder", SortDirection.Ascending)

        End If

        Me.AdminBudgetCategoriesDropDownList.Attributes.Add("onchange", "document.getElementById(""mainSection"").style.visibility=""hidden"";")
        Dim sDataKey(0) As String
        sDataKey(0) = "Id"
        Me.CategoryHeadingsScrollingGridView.DataKeyNames = sDataKey

    End Sub

    Private Sub SetupJavaScript()

        EntityController.JavaScriptAddChildDiv(Me.CategoryHeadingsScrollingGridView.DivClientId, CInt(Me.CategoryHeadingsScrollingGridView.ToolTip))
        ClientScript.RegisterStartupScript(Me.GetType(), "scrollDivs", EntityController.JavaScriptScrollingGridStartup(Me.CategoryHeadingsScrollingGridView), True)
        EntityController.JavaScriptSetFixedHeight(0)
        ScriptManager.RegisterClientScriptBlock(Me.CategoryHeadingsScrollingGridView, Me.CategoryHeadingsScrollingGridView.GetType(), _
        "scrollDivAsync", EntityController.JavaScriptScrollingGridStartup(Me.CategoryHeadingsScrollingGridView), True)
    End Sub


    Protected Sub AdminBudgetCategoriesDropDownList_SelectedIndexChanged(ByVal sender As Object, _
                                                                         ByVal e As System.EventArgs) _
                                                                         Handles AdminBudgetCategoriesDropDownList.SelectedIndexChanged

        Me.CatHeadingsObjectDataSource.SelectMethod = "ListBySort"
        Me.CategoryHeadingsScrollingGridView.DataBind()
        If Me.AdminBudgetCategoriesDropDownList.SelectedValue.Equals("10018") Then
            Me.CategoryHeadingsScrollingGridView.Columns(CategoryHeadingsScrollingGridView.Columns.Count - 1).Visible = False
            Response.Write("<script language='javascript'>alert('Savings for Purchases Column headers are read only, because of special calculations.');</script>")
        Else
            Me.CategoryHeadingsScrollingGridView.Columns(CategoryHeadingsScrollingGridView.Columns.Count - 1).Visible = True
        End If

    End Sub

    Protected Sub AdminBudgetCategoriesDetailsView_ItemInserted(ByVal sender As Object, _
                                                                ByVal e As System.Web.UI.WebControls.DetailsViewInsertedEventArgs) _
                                                                Handles AdminBudgetCategoriesDetailsView.ItemInserted

        Me.CatHeadingsObjectDataSource.Select()
        Me.CategoryHeadingsScrollingGridView.DataBind()

    End Sub

    Protected Sub AddButton_Click(ByVal sender As Object, _
                                  ByVal e As System.EventArgs) _
                                  Handles AddButton.Click

        Me.CategoryHeadingsScrollingGridView.Visible = False
        Me.AddButton.Visible = False
        Me.NewCatHeadingsObjectDataSource.Select()
        Me.AdminBudgetCategoriesDetailsView.DataBind()
        Me.AdminBudgetCategoriesDetailsView.Visible = True
        Me.SubmitButton.Visible = True
        Me.CancelButton.Visible = True

    End Sub

    Protected Sub SubmitButton_Click(ByVal sender As Object, _
                                     ByVal e As System.EventArgs) _
                                     Handles SubmitButton.Click

        Dim iBudgetCatId As Integer = Convert.ToInt32(Me.AdminBudgetCategoriesDropDownList.SelectedValue)
        Dim txtDisplayName As TextBox = CType(AdminBudgetCategoriesDetailsView.FindControl("DisplayNameDetailsTextBox"), TextBox)
        Dim txtDisplayOrder As TextBox = CType(AdminBudgetCategoriesDetailsView.FindControl("DisplayOrderDetailsTextBox"), TextBox)
        Dim txtColumnSpan As TextBox = CType(AdminBudgetCategoriesDetailsView.FindControl("ColumnSpanDetailsTextBox"), TextBox)
        Dim chkIsActive As CheckBox = CType(AdminBudgetCategoriesDetailsView.FindControl("IsActiveDetailsCheckBox"), CheckBox)
        Dim txtFormula As TextBox = CType(AdminBudgetCategoriesDetailsView.FindControl("FormulaTextBox"), TextBox)

        If (txtDisplayName.Text = "") Or (txtDisplayOrder.Text = "") Or (txtColumnSpan.Text = "") Then
            Dim strValue As String
            strValue = "Column Span, Display Order, and Display Name must be filled in before proceeding."
            Me.ErrorSummary.SetSingleError(strValue)
            Me.ErrorSummary.Visible = True
            isError = True
        End If

        If Not isError Then
            If ErrorSummary.Visible = True Then
                ErrorSummary.Visible = False
            End If

            Dim objCatHeader As Cdm.DataCore.LookupTables.LuAdminBudgetCategoryHeader
            objCatHeader = New Cdm.DataCore.LookupTables.LuAdminBudgetCategoryHeader()

            objCatHeader.DisplayName = txtDisplayName.Text
            objCatHeader.DisplayOrder = Convert.ToInt32(txtDisplayOrder.Text)
            objCatHeader.ColumnSpan = Convert.ToInt32(txtColumnSpan.Text)
            objCatHeader.IsActive = chkIsActive.Checked
            objCatHeader.BudgetCategoryId = iBudgetCatId
            objCatHeader.Formula = txtFormula.Text
            objCatHeader.Persist()

            Me.AdminBudgetCategoriesDetailsView.Visible = False

            Me.SubmitButton.Visible = False
            Me.CancelButton.Visible = False

            Me.CatHeadingsObjectDataSource.Select()
            Me.CategoryHeadingsScrollingGridView.DataBind()
            Me.CategoryHeadingsScrollingGridView.Visible = True
            Me.AddButton.Visible = True
        End If

    End Sub

    Protected Sub CancelButton_Click(ByVal sender As Object, _
                                     ByVal e As System.EventArgs) _
                                     Handles CancelButton.Click

        If ErrorSummary.Visible = True Then
            ErrorSummary.Visible = False
        End If

        Me.AdminBudgetCategoriesDetailsView.Visible = False
        Me.SubmitButton.Visible = False
        Me.CancelButton.Visible = False
        Me.CategoryHeadingsScrollingGridView.Visible = True
        Me.AddButton.Visible = True

    End Sub

    Private Function GetTotalColumnSpan(ByVal e As System.Web.UI.WebControls.GridViewUpdateEventArgs, _
                                        ByVal imageName As String) As Integer
        Dim totalColumnSpan As Integer = 0
        Dim displayImage As Image
        For i As Integer = 0 To Me.CategoryHeadingsScrollingGridView.Rows.Count - 1
            displayImage = Me.CategoryHeadingsScrollingGridView.Rows(i).FindControl(imageName)
            If displayImage.ImageUrl.Contains("greencheck.gif") Then
                If i = e.RowIndex Then
                    totalColumnSpan += e.NewValues(2)
                Else
                    Dim cellLiteral As System.Web.UI.DataBoundLiteralControl
                    cellLiteral = Me.CategoryHeadingsScrollingGridView.Rows(i).Cells(4).Controls(0)
                    totalColumnSpan += cellLiteral.Text
                    'totalColumnSpan += Me.CategoryHeadingsScrollingGridView.Rows(i).Cells(2).Text
                End If
            End If
        Next
        Return totalColumnSpan
    End Function

    Private Function IsChecked(ByVal iRow As Integer, _
                               ByVal imageName As String) As Integer
        Dim displayImage As Image
        displayImage = Me.CategoryHeadingsScrollingGridView.Rows(iRow).FindControl(imageName)
        If displayImage.ImageUrl.Contains("greencheck.gif") Then
            Return True
        Else
            Return False
        End If

    End Function

    ''' <summary>
    ''' This function is a check to make before updating a column header.
    ''' It checks if a formula includes a column that is either not in
    ''' a Spending plan or Expenditure Report.
    ''' </summary>
    ''' <param name="e"></param>
    ''' <returns>String with error message.  Empty string if there is none.</returns>
    ''' <remarks></remarks>
    Private Function GetThisFormulaInactiveHeadersMessage(ByVal e As System.Web.UI.WebControls.GridViewUpdateEventArgs) As String
       
        'If this row does not have a formula, then return blank.
        If String.IsNullOrEmpty(e.NewValues(NEWVALUES_FORMULA)) Then
            Return ""
        End If

        Dim columnDisplayName As String
        Dim newFormula As String = e.NewValues(NEWVALUES_FORMULA).ToString()

        Dim newExpenditureReportFormula As String = ""
        If Not String.IsNullOrEmpty(e.NewValues(NEWVALUES_EXPENDITUREFORMULA)) Then
            newExpenditureReportFormula = e.NewValues(NEWVALUES_EXPENDITUREFORMULA).ToString()
        Else
            newExpenditureReportFormula = newFormula
        End If

        Dim bShowOnSpendingPlan As Boolean = False
        Dim bShowOnExpenditureReport As Boolean = False

        For i As Integer = 0 To Me.CategoryHeadingsScrollingGridView.Rows.Count - 1
            If i <> e.RowIndex Then
                Dim cellLiteral As System.Web.UI.DataBoundLiteralControl
                cellLiteral = Me.CategoryHeadingsScrollingGridView.Rows(i).Cells(GRIDHEADER_DISPLAYNAME).Controls(0)
                columnDisplayName = "[" + cellLiteral.Text + "]"
                bShowOnSpendingPlan = IsChecked(i, "ShowOnSpendingPlanImage")
                bShowOnExpenditureReport = IsChecked(i, "ShowOnMonthlyStatementImage")
                If bShowOnSpendingPlan = False And newFormula.ToUpper.Contains(columnDisplayName.ToUpper()) Then
                    Return "The formula contains the column header " + columnDisplayName + ".  This column is not shown on spending plans.  " + _
                           "You will need to modify the formula to exclude this column, or modify the column to be shown on the spending plan."
                End If

                If bShowOnExpenditureReport = False And newExpenditureReportFormula.ToUpper.Contains(columnDisplayName.ToUpper()) Then
                    Return "The formula contains the column header " + columnDisplayName + ".  This column is not shown on expenditure reports.  " + _
                           "You will need to modify the formula to exclude this column, or modify the column to be shown on the expenditure report."
                End If
            End If

        Next
        Return ""
    End Function

    Private Function GetThisInactiveHeaderInAnActiveColumnHeaderMessage(ByVal e As System.Web.UI.WebControls.GridViewUpdateEventArgs, ByVal categoryheader As Cdm.DataCore.LookupTables.LuAdminBudgetCategoryHeader) As String
        If categoryheader.DisplayOnExpenditureReport And categoryheader.DisplayOnSpendingPlan Then
            Return ""
        End If
        Dim bExp As Boolean = categoryheader.DisplayOnExpenditureReport
        Dim bSP As Boolean = categoryheader.DisplayOnSpendingPlan
        Dim id As Integer = categoryheader.Id
        Return Cdm.DataCore.LookupTables.LuAdminBudgetCategoryHeader.CheckIfInActiveFieldInOtherFormulas(id, bExp, bSP)
    End Function

    Protected Sub CategoryHeadingsScrollingGridView_RowCancelingEdit(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewCancelEditEventArgs) Handles CategoryHeadingsScrollingGridView.RowCancelingEdit
        If ErrorSummary.Visible = True Then
            ErrorSummary.Visible = False
        End If
        SetStatus("Edit Cancelled.")
    End Sub

    Private Sub SetStatus(ByVal message As String)
        CategoryHeadingsScrollingGridView.StatusText = message
    End Sub

    Private Sub ClearStatus()
        SetStatus("")
    End Sub

    Protected Sub CategoryHeadingsScrollingGridView_RowDataBound(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewRowEventArgs) Handles CategoryHeadingsScrollingGridView.RowDataBound
        AccessibilityController.SetGridViewEditToolTips(e.Row, Me.CategoryHeadingsScrollingGridView)
        Dim txtDisplay As TextBox = CType(e.Row.FindControl("DisplayTextBox"), TextBox)
        If Not txtDisplay Is Nothing Then
            SetFocus(txtDisplay.ClientID)
        End If


        Dim header As Cdm.DataCore.LookupTables.LuAdminBudgetCategoryHeader = e.Row.DataItem
        Dim displayOnSpendingPlanImage As Image = e.Row.FindControl("ShowOnSpendingPlanImage")
        Dim displayOnMonthlyStatementImage As Image = e.Row.FindControl("ShowOnMonthlyStatementImage")
        Dim formatDropDownList As DropDownList = e.Row.FindControl("EditItemFormatDropDownList")
        If Not displayOnSpendingPlanImage Is Nothing Then
            If header.DisplayOnSpendingPlan Then
                displayOnSpendingPlanImage.ImageUrl = "~/images/greencheck.gif"
                displayOnSpendingPlanImage.AlternateText = "true"
            Else
                displayOnSpendingPlanImage.ImageUrl = "~/images/blankcheck.gif"
                displayOnSpendingPlanImage.AlternateText = "false"
            End If
        End If

        If Not displayOnMonthlyStatementImage Is Nothing Then
            If header.DisplayOnExpenditureReport Then
                displayOnMonthlyStatementImage.ImageUrl = "~/images/greencheck.gif"
                displayOnMonthlyStatementImage.AlternateText = "true"
            Else
                displayOnMonthlyStatementImage.ImageUrl = "~/images/blankcheck.gif"
                displayOnMonthlyStatementImage.AlternateText = "false"
            End If
        End If

        If Not formatDropDownList Is Nothing Then
            If Not String.IsNullOrEmpty(header.ItemFormat) Then
                formatDropDownList.SelectedValue = header.ItemFormat
            End If
            If header.IsTotalCostField Or header.IsDateOfService Then
                formatDropDownList.Enabled = False
            Else
                formatDropDownList.Enabled = True
            End If
        End If

    End Sub

    Protected Sub CategoryHeadingsScrollingGridView_RowUpdated(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewUpdatedEventArgs) Handles CategoryHeadingsScrollingGridView.RowUpdated
        SetStatus("Category Heading updated.")
    End Sub

    Protected Sub CategoryHeadingsScrollingGridView_RowUpdating(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewUpdateEventArgs) Handles CategoryHeadingsScrollingGridView.RowUpdating
        'Dim totalColumnSpanSpendingPlan As Integer = GetTotalColumnSpan(e, "ShowOnSpendingPlanImage")
        'Dim totalColumnSpanMonthlyStatement As Integer = GetTotalColumnSpan(e, "ShowOnMonthlyStatementImage")

        Dim key As DataKey
        key = CategoryHeadingsScrollingGridView.DataKeys(e.RowIndex)
        Dim categoryHeader As Cdm.DataCore.LookupTables.LuAdminBudgetCategoryHeader
        categoryHeader = Cdm.DataCore.LookupTables.LuAdminBudgetCategoryHeader.Retrieve(Convert.ToInt32(key.Value.ToString()))
        Dim showSpendingPlanCheckBox As CheckBox = CType(CategoryHeadingsScrollingGridView.Rows(e.RowIndex).FindControl("ShowOnSpendingPlanCheckBox"), CheckBox)
        Dim showExpenditureCheckBox As CheckBox = CType(CategoryHeadingsScrollingGridView.Rows(e.RowIndex).FindControl("ShowOnMonthlyStatementCheckBox"), CheckBox)
        categoryHeader.DisplayOnSpendingPlan = showSpendingPlanCheckBox.Checked
        categoryHeader.DisplayOnExpenditureReport = showExpenditureCheckBox.Checked
        Dim formatDropDown As DropDownList = CategoryHeadingsScrollingGridView.Rows(e.RowIndex).FindControl("EditItemFormatDropDownList")




        Dim thisFormulaIncludesInactiveHeadersString As String = GetThisFormulaInactiveHeadersMessage(e)
        Dim thisColumnInactiveButInAnotherFormulaString As String = GetThisInactiveHeaderInAnActiveColumnHeaderMessage(e, categoryHeader)
        Dim newFormula As String = ""
        Dim newExpFormula As String = ""
        Dim newItemFormat As String = ""

        Dim editErrorSummary As InputControls.ValidationErrorSummary = CType(CategoryHeadingsScrollingGridView.Rows(e.RowIndex).FindControl("EditErrorSummary"), InputControls.ValidationErrorSummary)

        If Not (e.NewValues.Item(NEWVALUES_FORMULA)) Is Nothing Then
            newFormula = e.NewValues.Item(NEWVALUES_FORMULA).ToString()
        End If

        If Not (e.NewValues.Item(NEWVALUES_EXPENDITUREFORMULA)) Is Nothing Then
            newExpFormula = e.NewValues.Item(NEWVALUES_EXPENDITUREFORMULA).ToString()
        End If

        If Not formatDropDown Is Nothing Then
            newItemFormat = formatDropDown.SelectedValue
        End If

        If Not String.IsNullOrEmpty(thisFormulaIncludesInactiveHeadersString) Then
            editErrorSummary.SetSingleError(thisFormulaIncludesInactiveHeadersString)
            e.Cancel = True
            editErrorSummary.Visible = True
        ElseIf Not String.IsNullOrEmpty(thisColumnInactiveButInAnotherFormulaString) Then
            editErrorSummary.SetSingleError(thisColumnInactiveButInAnotherFormulaString)
            e.Cancel = True
            editErrorSummary.Visible = True
        ElseIf Not IsNumeric(e.NewValues.Item(NEWVALUES_COLUMNWIDTH).ToString()) Then
            message = "Column Width value must be a valid number."
            editErrorSummary.SetSingleError(message)
            e.Cancel = True
            editErrorSummary.Visible = True
        ElseIf Not IsNumeric(e.NewValues.Item(NEWVALUES_DISPLAYORDER).ToString()) Then
            message = "Display Order value must be a valid number."
            editErrorSummary.SetSingleError(message)
            e.Cancel = True
            editErrorSummary.Visible = True
        ElseIf Not IsNumeric(e.NewValues.Item(NEWVALUES_COLUMNSPAN).ToString()) Then
            message = "Column Span must be a valid number."
            editErrorSummary.SetSingleError(message)
            e.Cancel = True
            editErrorSummary.Visible = True
        ElseIf newFormula.Length > 0 And Not (newFormula.StartsWith("=")) Then
            message = "If a formula is entered, is must begin with '='"
            editErrorSummary.SetSingleError(message)
            e.Cancel = True
            editErrorSummary.Visible = True
        ElseIf newExpFormula.Length > 0 And Not (newExpFormula.StartsWith("=")) _
               And Not newExpFormula.Equals("[None]") Then
            message = "If a formula is entered, is must begin with '=', or enter [None]"
            editErrorSummary.SetSingleError(message)
            e.Cancel = True
            editErrorSummary.Visible = True
        Else
            'Manually update the record



            'displayname,displayorder,columnspan,isactive
            categoryHeader.DisplayName = e.NewValues().Item(NEWVALUES_DISPLAYNAME).ToString
            categoryHeader.ColumnWidth = Convert.ToInt32(e.NewValues().Item(NEWVALUES_COLUMNWIDTH))
            categoryHeader.DisplayOrder = Convert.ToInt32(e.NewValues().Item(NEWVALUES_DISPLAYORDER))
            categoryHeader.ColumnSpan = Convert.ToInt32(e.NewValues().Item(NEWVALUES_COLUMNSPAN))
            categoryHeader.ItemFormat = newItemFormat
            If IsNothing(e.NewValues().Item(NEWVALUES_FORMULA)) Then
                categoryHeader.Formula = ""
                categoryHeader.IsInFormula = False
            Else
                categoryHeader.Formula = e.NewValues().Item(NEWVALUES_FORMULA).ToString()
                categoryHeader.IsInFormula = True
            End If



            If IsNothing(e.NewValues().Item(NEWVALUES_EXPENDITUREFORMULA)) Then
                categoryHeader.ExpenditureReportFormula = ""
            Else
                categoryHeader.ExpenditureReportFormula = e.NewValues().Item(NEWVALUES_EXPENDITUREFORMULA).ToString()
            End If



            'categoryHeader.IsActive = Convert.ToBoolean(e.NewValues().Item(3))
            Dim trans As New Gentle.Framework.Transaction()
            Try
                categoryHeader.Persist(trans)
                categoryHeader.UpdateFormulas(e.OldValues.Item(NEWVALUES_DISPLAYNAME).ToString(), e.NewValues(NEWVALUES_DISPLAYNAME).ToString(), trans)
                trans.Commit()
            Catch ex As Exception
                trans.Rollback()
                Me.ErrorSummary.Message = "Error updating category header information."
                Me.ErrorSummary.SetSingleError(ex.Message)
                Me.ErrorSummary.Visible = True
            End Try
            e.Cancel = True
            Me.CategoryHeadingsScrollingGridView.EditIndex = -1
        End If

    End Sub
End Class
